package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.pojo.Bom;
import com.zhentao.pojo.BomItem;
import com.zhentao.pojo.Product;
import com.zhentao.mapper.BomMapper;
import com.zhentao.mapper.BomItemMapper;
import com.zhentao.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * BOM管理控制器
 * @date: 2025/8/13 8:49
 * @author: ftt
 */
@RestController
@RequestMapping("/produce/bom")
@CrossOrigin
public class BomController {

    @Autowired
    private BomMapper bomMapper;

    @Autowired
    private BomItemMapper bomItemMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 分页查询BOM列表
     */
    @GetMapping("/list")
    public Page<Bom> list(@RequestParam(defaultValue = "1") Integer current,
                          @RequestParam(defaultValue = "10") Integer size,
                          @RequestParam(required = false) String name,
                          @RequestParam(required = false) Long productId,
                          @RequestParam(required = false) Integer status) {
        
        Page<Bom> page = new Page<>(current, size);
        QueryWrapper<Bom> queryWrapper = new QueryWrapper<>();
        
        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);
        }
        if (productId != null) {
            queryWrapper.eq("product_id", productId);
        }
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        queryWrapper.orderByDesc("id");
        
        return bomMapper.selectPage(page, queryWrapper);
    }

    /**
     * 根据ID查询BOM详情
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> getDetail(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 查询BOM主表信息
        Bom bom = bomMapper.selectById(id);
        if (bom == null) {
            result.put("success", false);
            result.put("message", "BOM不存在");
            return result;
        }
        
        // 查询BOM明细
        QueryWrapper<BomItem> itemWrapper = new QueryWrapper<>();
        itemWrapper.eq("bom_id", id);
        List<BomItem> items = bomItemMapper.selectList(itemWrapper);
        
        // 查询产品信息
        Product product = productMapper.selectById(bom.getProductId());
        
        result.put("success", true);
        result.put("bom", bom);
        result.put("items", items);
        result.put("product", product);
        
        return result;
    }

    /**
     * 新增BOM
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 解析BOM主表信息
            Bom bom = new Bom();
            bom.setProductId(Long.valueOf(request.get("productId").toString()));
            bom.setName(request.get("name").toString());
            bom.setVersion(request.get("version").toString());
            bom.setStatus(Integer.valueOf(request.get("status").toString()));
            bom.setTenantId(1L); // 默认租户ID
            
            // 插入BOM主表
            bomMapper.insert(bom);
            
            // 解析并插入BOM明细
            List<Map<String, Object>> items = (List<Map<String, Object>>) request.get("items");
            if (items != null && !items.isEmpty()) {
                for (Map<String, Object> item : items) {
                    BomItem bomItem = new BomItem();
                    bomItem.setBomId(bom.getId());
                    bomItem.setMaterialId(Long.valueOf(item.get("materialId").toString()));
                    bomItem.setQuantity(new java.math.BigDecimal(item.get("quantity").toString()));
                    bomItem.setProcess(item.get("process") != null ? item.get("process").toString() : "");
                    
                    bomItemMapper.insert(bomItem);
                }
            }
            
            result.put("success", true);
            result.put("message", "BOM创建成功");
            result.put("id", bom.getId());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "BOM创建失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 更新BOM
     */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Long bomId = Long.valueOf(request.get("id").toString());
            
            // 检查BOM是否存在
            Bom existingBom = bomMapper.selectById(bomId);
            if (existingBom == null) {
                result.put("success", false);
                result.put("message", "BOM不存在");
                return result;
            }
            
            // 更新BOM主表信息
            Bom bom = new Bom();
            bom.setId(bomId);
            bom.setProductId(Long.valueOf(request.get("productId").toString()));
            bom.setName(request.get("name").toString());
            bom.setVersion(request.get("version").toString());
            bom.setStatus(Integer.valueOf(request.get("status").toString()));
            
            bomMapper.updateById(bom);
            
            // 删除原有明细
            QueryWrapper<BomItem> deleteWrapper = new QueryWrapper<>();
            deleteWrapper.eq("bom_id", bomId);
            bomItemMapper.delete(deleteWrapper);
            
            // 插入新的明细
            List<Map<String, Object>> items = (List<Map<String, Object>>) request.get("items");
            if (items != null && !items.isEmpty()) {
                for (Map<String, Object> item : items) {
                    BomItem bomItem = new BomItem();
                    bomItem.setBomId(bomId);
                    bomItem.setMaterialId(Long.valueOf(item.get("materialId").toString()));
                    bomItem.setQuantity(new java.math.BigDecimal(item.get("quantity").toString()));
                    bomItem.setProcess(item.get("process") != null ? item.get("process").toString() : "");
                    
                    bomItemMapper.insert(bomItem);
                }
            }
            
            result.put("success", true);
            result.put("message", "BOM更新成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "BOM更新失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除BOM
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查BOM是否存在
            Bom bom = bomMapper.selectById(id);
            if (bom == null) {
                result.put("success", false);
                result.put("message", "BOM不存在");
                return result;
            }
            
            // 删除BOM明细
            QueryWrapper<BomItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("bom_id", id);
            bomItemMapper.delete(itemWrapper);
            
            // 删除BOM主表
            bomMapper.deleteById(id);
            
            result.put("success", true);
            result.put("message", "BOM删除成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "BOM删除失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取产品列表（用于下拉选择）
     */
    @GetMapping("/products")
    public List<Product> getProducts() {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 只查询启用的产品
        queryWrapper.orderByAsc("name");
        return productMapper.selectList(queryWrapper);
    }

    /**
     * 根据产品ID查询BOM列表
     */
    @GetMapping("/byProduct/{productId}")
    public List<Bom> getBomsByProduct(@PathVariable Long productId) {
        QueryWrapper<Bom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_id", productId);
        queryWrapper.eq("status", 1); // 只查询启用的BOM
        queryWrapper.orderByDesc("version");
        return bomMapper.selectList(queryWrapper);
    }

    /**
     * 批量删除BOM
     */
    @DeleteMapping("/batchDelete")
    public Map<String, Object> batchDelete(@RequestBody List<Long> ids) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            for (Long id : ids) {
                // 删除BOM明细
                QueryWrapper<BomItem> itemWrapper = new QueryWrapper<>();
                itemWrapper.eq("bom_id", id);
                bomItemMapper.delete(itemWrapper);
                
                // 删除BOM主表
                bomMapper.deleteById(id);
            }
            
            result.put("success", true);
            result.put("message", "批量删除成功，共删除 " + ids.size() + " 条记录");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量删除失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 复制BOM
     */
    @PostMapping("/copy/{id}")
    public Map<String, Object> copyBom(@PathVariable Long id, @RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 查询原BOM
            Bom originalBom = bomMapper.selectById(id);
            if (originalBom == null) {
                result.put("success", false);
                result.put("message", "原BOM不存在");
                return result;
            }
            
            // 创建新的BOM
            Bom newBom = new Bom();
            newBom.setProductId(originalBom.getProductId());
            newBom.setName(request.get("name").toString());
            newBom.setVersion(request.get("version").toString());
            newBom.setStatus(Integer.valueOf(request.get("status").toString()));
            newBom.setTenantId(originalBom.getTenantId());
            
            bomMapper.insert(newBom);
            
            // 复制BOM明细
            QueryWrapper<BomItem> itemWrapper = new QueryWrapper<>();
            itemWrapper.eq("bom_id", id);
            List<BomItem> originalItems = bomItemMapper.selectList(itemWrapper);
            
            for (BomItem originalItem : originalItems) {
                BomItem newItem = new BomItem();
                newItem.setBomId(newBom.getId());
                newItem.setMaterialId(originalItem.getMaterialId());
                newItem.setQuantity(originalItem.getQuantity());
                newItem.setProcess(originalItem.getProcess());
                
                bomItemMapper.insert(newItem);
            }
            
            result.put("success", true);
            result.put("message", "BOM复制成功");
            result.put("id", newBom.getId());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "BOM复制失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 启用/禁用BOM
     */
    @PutMapping("/toggleStatus/{id}")
    public Map<String, Object> toggleStatus(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Bom bom = bomMapper.selectById(id);
            if (bom == null) {
                result.put("success", false);
                result.put("message", "BOM不存在");
                return result;
            }
            
            // 切换状态
            bom.setStatus(bom.getStatus() == 1 ? 0 : 1);
            bomMapper.updateById(bom);
            
            result.put("success", true);
            result.put("message", "状态更新成功");
            result.put("status", bom.getStatus());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "状态更新失败: " + e.getMessage());
        }
        
        return result;
    }
}
